package com.seeyon.bugfixtools.workflow.dao;

import com.seeyon.bugfixtools.workflow.dto.ScanLockResDto;
import org.springframework.context.annotation.Lazy;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Repository
public class WorkflowLockDao {

    @Lazy
    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 扫描锁信息
     *
     * @return
     */
    public List<ScanLockResDto> scanLock() {
        String sql = "SELECT cs.SUBJECT processName,l.OWNER AS ownerId, l.lock_timemillis AS lockTime, l.id AS lockId, c.id AS caseId " +
                "FROM ctp_lock l LEFT JOIN wf_case_run c ON c.id = l.RESOURCE_ID " +
                "left join col_summary cs on cs.PROCESS_ID = c.PROCESSID " +
                "WHERE c.id IS NOT NULL " +
                "UNION " +
                "SELECT cs.SUBJECT processName,l.OWNER AS ownerId, l.lock_timemillis AS lockTime, l.id AS lockId, c.id AS caseId " +
                "FROM ctp_lock l LEFT JOIN wf_case_history c ON c.id = l.RESOURCE_ID " +
                "left join col_summary cs on cs.PROCESS_ID = c.PROCESSID " +
                "WHERE c.id IS NOT NULL";


        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            ScanLockResDto dto = new ScanLockResDto();
            // 手动映射查询结果到 ScanLockResDto 类的实例
            dto.setProcessName(rs.getString("processName"));
            dto.setOwnerId(rs.getString("ownerId"));
            dto.setLockTime(rs.getLong("lockTime"));
            dto.setLockId(rs.getString("lockId"));
            dto.setCaseId(rs.getString("caseId"));
            if (dto.getLockTime() != null) {
                LocalDateTime datetime = LocalDateTime.ofInstant(Instant.ofEpochMilli(dto.getLockTime()), ZoneId.systemDefault());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                dto.setLockTimeStr(datetime.format(formatter));
                long minutes = (System.currentTimeMillis() - dto.getLockTime()) / (60 * 1000);
                dto.setAlreadyLockedMinutes(minutes);
            }
            return dto;
        });

    }


    public void deleteLock(Long lockId) {
        String sql = "delete from ctp_lock where id = " + lockId;
        jdbcTemplate.execute(sql);
    }
}
